// @flow
import React from 'react'
import moment from 'moment'
import styles from './HistoryLine.css'
import { Modal, Tabs, Tag } from 'antd'
// import Highcharts from 'highcharts-release'
import HighStock from 'highcharts-release/highstock.js'
import HighchartsCustomEvents from 'highcharts-custom-events'
import basicContext from 'basiccontext'
import 'basiccontext/dist/basicContext.min.css'
import 'basiccontext/dist/themes/bright.min.css'
import 'basiccontext/dist/addons/popin.min.css'
import HistoryPolar from 'components/HistoryPolar'
import HistoryPolarAxis from 'components/HistoryPolarAxis'
import Spectrum from 'components/Spectrum'
import Bode from 'components/Bode'
import AddChartEvent from 'components/AddChartEvent'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import R from 'ramda'
import ReactDom from 'react-dom'
import { connect } from 'react-redux'
import { changeHistoryChartCond,
  changeDynamicChartCond, changeDynamicDateCond } from 'store/modules/deviceFileCondition'
const TabPane = Tabs.TabPane
// import theme from './theme.js'
HighchartsCustomEvents(HighStock)

import type { Location } from 'react-router'
const { search } = location
const paramsString = search.substring(1)
const searchParams = new URLSearchParams(paramsString)
const requestType = searchParams.get('requestType')

type Props = {
  // xData: Array<any>,
  // historyFrom: number,
  // historyTo: number,
  location: Location,
  chartData: Array<any>,
  title: String,
  yTitle: String,
  showContextMenu?: boolean,
  type?: string,
  deviceCard: Object,
  updateEvents: Function,
  deviceFileCondition: Object,
  userId: string
}

type States = {
  spectrumVisible: boolean,
  visible: boolean,
  checkTime: any,
  checkName: string,
  activeKey: string,
  channel_id: number
}
let innerChart = {}
class HistoryLine extends React.Component {
  props: Props
  state: States
  chart: Object
  addEvents: Function
  showChart: Function
  closeModal: Function
  removeEventsModal: Function
  changeTab: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      spectrumVisible: false,
      visible: false,
      checkTime: '',
      checkName: '',
      activeKey: 'spectrum',
      channel_id: 0
    }
    this.addEvents = this.addEvents.bind(this)
    this.showChart = this.showChart.bind(this)
    this.changeTab = this.changeTab.bind(this)
    this.closeModal = this.closeModal.bind(this)
    this.removeEventsModal = this.removeEventsModal.bind(this)
  }

  componentDidMount () {
    this.draw(this.props)
  }
  componentWillReceiveProps (nextProps: Props) {
    if (!R.equals(nextProps, this.props)) {
      this.draw(nextProps)
    }
  }

  addEvents (e: Object) {
    const { x, series } = e.point
    const { deviceCard, updateEvents, userId } = this.props
    const container = this.refs.chartEvent
    let api = `${__SERVICE_API__}`
    if (requestType === 'wx') {
      api = `${__WXSERVICE_API__}`
    }
    universalFetch(`${api}sys/users/${userId}`)
      .then(res => res.json())
      .then((json) => {
        const userName = json.result.name
        ReactDom.render(
          <AddChartEvent {...{
            userName,
            eventTime: x,
            deviceCard,
            updateEvents,
            removeEventsModal: this.removeEventsModal,
            channel_id: series.options.compoundId.channel_id,
            variableNameEn: series.options.field,
            sensorNameEn: series.options.sensorNameEn,
            sensorName: series.options.sensorName,
            checkName: series.name
          }} />,
          container
        )
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  removeEventsModal () {
    const container = this.refs.chartEvent
    ReactDom.unmountComponentAtNode(container)
  }
  closeModal () {
    this.setState({
      visible: false
    })
  }
  showChart (e: Object, active) {
    const { x, series } = e.point
    // series.name.split('__')[1]
    this.setState({
      visible: true,
      checkTime: x,
      channel_id: series.options.compoundId.channel_id,
      checkName: series.name, // '通频值__YT111A'
      activeKey: active
    })
  }
  changeTab (key: string) {
    this.setState({
      activeKey: key
    })
  }
  draw (props: Props) {
    const that = this
    const container = this.refs.container
    const { type } = this.props
    // 如果是移动端访问就改为点击事件，否則是右击事件
    let eventType = 'contextmenu'
    if (requestType === 'wx') {
      eventType = 'click'
    }
    // y轴的最小值（如果都是正数，最小值为0，有负数就不设置最小值）
    let minValue = 0
    props.chartData.map((d, i) => {
      d.data.map((dd, ii) => {
        if (dd[1] < 0) {
          minValue = null
        }
      })
    })
    HighStock.setOptions({ global: { useUTC: false } })
    innerChart = HighStock.StockChart(container, {
      chart: {
        backgroundColor: 'transparent',
        zoomType: 'x'
      },
      rangeSelector : {
        enabled: false,
        buttons : [{
          type : 'all',
          count : 1,
          text : 'All'
        }],
        selected : 1,
        inputEnabled : false
      },
      title: {
        text: props.title,
        x: -20
      },
      credits:{
        enabled: false
      },
      legend: {
        enabled: true,
        verticalAlign: 'top'
      },
      tooltip: {
        shared: true,
        useHTML: true,
        formatter: function () {
          let t = '<b>' + moment(this.x, 'x').format('YYYY-MM-DD HH:mm:ss') + '</b>' +
            '<table>'
          const y1 = this.y.toFixed(3) * 1000 / 1000
          if (type === 'scatter') {
            t += '<tr><td style="color: ' + this.series.color + '">' + this.series.name + ': </td>' +
              '<td style="text-align: right"><b>' + y1 + '</b></td></tr>'
          } else {
            this.points.map(function (d, i) {
              const y = d.y.toFixed(3) * 1000 / 1000
              t += '<tr><td style="color: ' + d.series.color + '">' + d.series.name + ': </td>' +
              '<td style="text-align: right"><b>' + y + '</b></td></tr>'
            })
          }
          t += '</table>'

          return t
        }
        // valueDecimals: 2
      },
      xAxis: {
        type: 'datetime',
        dateTimeLabelFormats: {
          second: '%Y-%m-%d<br>%H:%M:%S',
          minute: '%Y-%m-%d<br>%H:%M',
          hour: '%Y-%m-%d<br>%H:%M',
          day: '%Y-%m-%d',
          week: '%Y-%m-%d',
          month: '%Y-%m',
          year: '%Y'
        },
        // categories: this.props.xData,
        plotBands: [{
          color: 'rgba(68, 170, 213, .2)'
          // from: props.historyFrom,
          // to: props.historyTo
        }]
      },
      yAxis: {
        opposite: false,
        lineWidth: 1,
        min: minValue,
        title: {
          align: 'high',
          offset: 0,
          rotation: 0,
          y: -10,
          text: props.yTitle
        },
        plotLines: [{
          value: 0,
          width: 1,
          color: '#808080'
        }]
      },
      navigator: {
        height: 30,
        yAxis: {
          min: minValue
        }
      },
      plotOptions: {
        line: {
          lineWidth: 1,
          dataGrouping: {
            enabled: false
          }
        },
        series: {
          animation: true,
          point: {
            events: {
              [eventType]: (e) => {
                if (!this.props.showContextMenu) {
                  const contextMenu = [
                    {
                      title: '添加事件',
                      icon: 'fa fa-plus',
                      fn: () => {
                        that.addEvents(e)
                      }
                    },
                    {
                      title: '波形频谱图',
                      icon: 'fa fa-line-chart',
                      fn: () => {
                        that.showChart(e, 'spectrum')
                      }
                    },
                    {
                      title: '原始轴心轨迹图',
                      icon: 'fa fa-eercast',
                      fn: () => {
                        that.showChart(e, 'polarAxis')
                      }
                    },
                    {
                      title: '合成轴心轨迹图',
                      icon: 'fa fa-bullseye',
                      fn: () => {
                        that.showChart(e, 'polar')
                      }
                    },
                    {
                      title: '伯德图',
                      icon: 'fa fa-area-chart',
                      fn: () => {
                        that.showChart(e, 'bode')
                      }
                    }
                  ]
                  if (eventType === 'click') {
                    contextMenu.splice(0, 1)
                  }

                  basicContext.show(contextMenu, e)
                }
              }
            }
          }
        }
      },
      series: props.chartData
    })
    setTimeout(() => {
      innerChart.reflow()
    }, 5)
  }

  render () {
    const { visible, checkTime, activeKey, checkName, channel_id } = this.state
    const { type, deviceCard, deviceFileCondition } = this.props
    const title = deviceCard.deviceData.customerName + '/' + deviceCard.deviceData.name
    const operations = <Tag style={{ marginRight: 20, cursor: 'default' }}>设备：{title}</Tag>
    return (
      <div>
        <div ref='container' className={styles['container']} />
        <div ref='chartEvent' />
        <Modal
          width={1000}
          style={{ top: '5%' }}
          maskClosable={false}
          visible={visible}
          onCancel={this.closeModal}
          footer={null}
          header={null}
          >
          <div>
            <Tabs tabBarExtraContent={operations} activeKey={activeKey} size='small' onChange={this.changeTab}>
              <TabPane tab='波形频谱图' key='spectrum'>
                <Spectrum {...{
                  type,
                  historyCond: deviceFileCondition.historyCond,
                  deviceData: deviceCard.deviceData,
                  checkTime,
                  checkName,
                  channel_id
                }} />
              </TabPane>
              <TabPane tab='原始轴心轨迹图' key='polarAxis'>
                <HistoryPolarAxis {...{
                  historyCond: deviceFileCondition.historyCond,
                  deviceData: deviceCard.deviceData,
                  channel_id,
                  checkTime
                }} />
              </TabPane>
              <TabPane tab='合成轴心轨迹图' key='polar'>
                <HistoryPolar {...{
                  historyCond: deviceFileCondition.historyCond,
                  deviceData: deviceCard.deviceData,
                  channel_id,
                  checkTime
                }} />
              </TabPane>
              <TabPane tab='伯德图' key='bode'>
                <Bode {...{
                  historyCond: deviceFileCondition.historyCond,
                  deviceData: deviceCard.deviceData,
                  channel_id
                }} />
              </TabPane>
            </Tabs>
          </div>
        </Modal>
      </div>
    )
  }
}

const mapStatesToProps = (state) => {
  return {
    deviceCard: state.deviceCard,
    deviceFileCondition: state.deviceFileCondition,
    userId: state.user.userId
  }
}
export default connect(mapStatesToProps, {
  changeHistoryChartCond, changeDynamicChartCond, changeDynamicDateCond })(HistoryLine)
